#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "shmem.h"
#include "cJSON.h"

union val_t
{
    int b_val;
    int i_val;
    float f_val;
};

struct msg_queue
{
    long type;
    int key;
    union val_t val;
};

struct std_node
{
    int key;
    int type;
    int dev_type;
    union val_t old_val;
    union val_t new_val;
    int ret;
};

#define MAX_NODE 128
#define STD_NODE_LEN sizeof(struct std_node)
#define MAX_NODE_SIZE (MAX_NODE * STD_NODE_LEN)

static struct shm_param para;
static int *total;                // 指向共享内存中数据节点总个数
static struct std_node *node_arr; // 指向共享内存中节点缓存数组头
struct msg_queue msg;

int main(int argc, char const *argv[])
{
    int ret = -1;
    ret = shm_init(&para, "shm", MAX_NODE_SIZE);
    if (ret < 0)
    {
        return -1;
    }

    void *node_p = shm_getaddr(&para);
    if (node_p == NULL)
    {
        return -1;
    }

    // 前4个字节存储实际的学生数目
    total = (int *)node_p;
    // 后面空间存储数据点
    node_arr = (struct std_node *)(node_p + sizeof(int));
    printf("total=%d\n", *total);

    node_arr[0].type = 3;
    node_arr[0].key = 301;
    node_arr[0].new_val.f_val = 78.5;

    node_arr[1].type = 3;
    node_arr[1].key = 302;
    node_arr[1].new_val.f_val = 25.5;

    node_arr[2].type = 1;
    node_arr[2].key = 303;
    node_arr[2].new_val.b_val = 1;

    node_arr[3].type = 1;
    node_arr[3].key = 304;
    node_arr[3].new_val.b_val = 1;

    node_arr[4].type = 1;
    node_arr[4].key = 305;
    node_arr[4].new_val.b_val = 1;

    node_arr[5].type = 1;
    node_arr[5].key = 306;
    node_arr[5].new_val.b_val = 1;

    node_arr[6].type = 1;
    node_arr[6].key = 307;
    node_arr[6].new_val.b_val = 1;

    while (1)
    {
        if (msg_queue_recv("msg", &msg, sizeof(struct msg_queue), 0, 0) > 0)
        {
            printf("recv from msga type = %ld\n", msg.type);
            printf("recv from msga data = %d\n", msg.key);
            printf("recv from msga val = %d\n", msg.val.b_val);
        }
        else
        {
            perror("recv error:");
            return -1;
        }
    }
}